package org.groupg.practice.pool2.demo01;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.groupg.practice.pool2.demo01.model.ComplexObject;

public class ComplexObjectFactory extends BasePooledObjectFactory<ComplexObject> {
    @Override
    public ComplexObject create() {
        return new ComplexObject();
    }

    @Override
    public PooledObject<ComplexObject> wrap(ComplexObject complexObject) {
        return new DefaultPooledObject<>(complexObject);
    }

    public boolean validateObject(ComplexObject complexObject) {
        // 检查对象是否仍然有效
        return complexObject != null && complexObject.getData().length > 0;
    }

    /**
     * Always returns {@code true}.
     *
     * @param p ignored
     * @return {@code true}
     */
    @Override
    public boolean validateObject(PooledObject<ComplexObject> p) {
        return p.getObject() != null && p.getObject().getData().length > 0;
    }

    @Override
    public void passivateObject(PooledObject<ComplexObject> p) throws Exception {
        ComplexObject complexObject = p.getObject();
        // 清理对象，为下一次使用做准备
        complexObject.setText(null);
        complexObject.setNumber(0);
        complexObject.setValue(0);
        // 通常不需要清空整个数组，但可以设置为默认值或模式数据
        complexObject.setData(new byte[10]);
        complexObject.getDetails().clear();
        complexObject.getItems().clear();
    }
}